package com.lyz.dataStructure.LeetCode.stack;

import com.lyz.dataStructure.test.Test;

import java.util.Scanner;
import java.util.Stack;

/**
 * @Author:759057893@qq.com Lyz
 * @Date: 2019/5/6 21:07
 * @Description:
 **/

/*
给定一个只包括 '('，')'，'{'，'}'，'['，']' 的字符串，判断字符串是否有效
示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true
 */
public class Test1 {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s = in.nextLine();
            Test1 test1 = new Test1();
            System.out.println(test1.isValid(s));
        }
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            switch (ch){
                case '(':
                case '{':
                case '[':
                    //压栈
                    stack.push(ch);
                    break;
                case ')':
                case '}':
                case ']':
                    if(stack.isEmpty()){
                        return false;
                    } else {
                        //出栈并匹配括号
                        char left = stack.pop();
                        if(!((left == '(' && ch == ')') || (left == '{' && ch == '}') ||(left == '[' && ch == ']'))){
                            return false;
                        }
                        break;
                    }
                default:
                    break;
            }
        }
        //空栈
        if(stack.isEmpty()){
            return true;
        } else {
            return false;
        }
    }
}